/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

package guiexample;

import java.awt.Color;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.Image;
import java.awt.Rectangle;
import java.awt.RenderingHints;
import java.awt.Shape;
import java.awt.geom.AffineTransform;
import java.awt.geom.Rectangle2D;
import javax.swing.JFrame;
import java.awt.image.BufferStrategy;

public class TankView extends JFrame {

    Tank tank = null; //new Tank();
    TankController controller = null;
    Image image = null;
    BufferStrategy bS;
    public TankView(Tank tank, TankController controller) {
        //initial values for tank
        this.tank = tank;
        this.controller = controller;
        this.addMouseListener(controller);
        this.addKeyListener(controller);
        this.addMouseMotionListener(controller);
        tank.setX(250);
        tank.setY(100);
        tank.setWidth(20);
        tank.setHeight(28);
        tank.setAngle(0);
        tank.ra = 30;
        this.controller.setTank(tank);
        image = createImage(getWidth(), getHeight() );

    }
    public void init(){
        createBufferStrategy(2); //double buffering
        bS = getBufferStrategy();
    }

    public void paint(Graphics g) {
        //move the tank across the screen
        if( image == null ){
            image = createImage(getWidth(), getHeight());
            System.out.println("Recreated");
            return;
        }
        Graphics2D bg = (Graphics2D)image.getGraphics();
        bg.setRenderingHint(RenderingHints.KEY_ANTIALIASING,
					RenderingHints.VALUE_ANTIALIAS_ON);
        bg.setColor(Color.white);
        bg.fillRect(0, 0, getWidth(), getHeight());
        bg.setColor(Color.black);
        int currentX = (int)tank.getX();
        int currentY = (int)tank.getY();
        int width = (int)tank.getWidth();
        int height = (int)tank.getHeight();
        double rotationRadians = tank.getAngle()*(Math.PI/180);
        AffineTransform oldT = bg.getTransform();
        AffineTransform newT = new AffineTransform();
        newT.rotate(tank.getAngle(), tank.getX() + tank.getWidth()/2, tank.getY() + tank.getHeight()/2);
        bg.setTransform(newT);
        bg.fill(new Rectangle2D.Double(tank.getX(), tank.getY(), tank.getWidth(), tank.getHeight()));
        bg.setTransform(oldT);        
        bg.drawLine(this.controller.centreX, this.controller.centreY, (int)tank.tx, (int)tank.ty);
        g.drawImage(image, 0, 0, this);
        System.out.println("Tank's angle: " + tank.getAngle());
        System.out.println("Turret's angle: " + Math.toDegrees(this.controller.angle));
    }
}
